package cn.dceast.user.controller;


import cn.dceast.common.AccessLevel;
import cn.dceast.common.AccessPolicy;
import cn.dceast.common.UserLevel;
import cn.dceast.common.data.RtnData;
import cn.dceast.common.utils.DateUtil;
import cn.dceast.common.utils.Md5Utils;
import cn.dceast.common.utils.SecurityUtil;
import cn.dceast.common.utils.StringUtil;
import cn.dceast.user.model.UserInfo;
import cn.dceast.user.service.UserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.catalina.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/user")
public class UserController {

    public static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/index.html")
    public String index() {
        return "index/index";
    }
    /**
     * 进入登陆页面
     *
     * @return
     */
    @RequestMapping(value = "/register.html")
    public String register() {
        return "user/register";
    }

    /**
     * 用户注册
     *
     * @param userInfo
     * @param session
     * @return
     */
    @RequestMapping(value = "/addUser.do", method = RequestMethod.POST)
    @ResponseBody
    public RtnData addUser(UserInfo userInfo, HttpSession session) throws Exception {
        /*if (!(userInfo.getCode().equalsIgnoreCase(session.getAttribute("code").toString()))) {  //忽略验证码大小写
            return RtnData.fail("验证码错误！");
        } else {*/
            if (userService.verification(userInfo.getUsername()) > 0) {
                return RtnData.fail("用户名重复！");
            }
            if (userService.verification(userInfo.getMobile()) > 0) {
                return RtnData.fail("手机号已注册！");
            }
            if (userService.verification(userInfo.getEmail()) > 0) {
                return RtnData.fail("邮箱已注册！");
            }
            userInfo.setCreatetime(new Date());
            userInfo.setPassword(Md5Utils.encodeString(userInfo.getPassword()));//密码进行md5加密
            try {
                if (userService.register(userInfo) > 0) {
                    return RtnData.ok("注册成功");
                } else {
                    return RtnData.fail("注册失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("======用户注册失败======", e);
            }

            return RtnData.fail("注册失败");
        //}
    }
    /**
     * 获取用户信息
     * @param session
     * @return
     */
    @RequestMapping(value = "/getUserInfo.do", method = RequestMethod.GET)
    @ResponseBody
    public RtnData getUserInfo(HttpSession session) throws Exception {
        Integer userid = (Integer)session.getAttribute("userid");
        if (null != userid){
            UserInfo map = userService.getUser(userid);
            return  RtnData.ok(map);
        }else{
            return RtnData.ok(null);
        }


    }
    /**
     * 更新用户信息
     *
     * @param userInfo
     * @param session
     * @return
     */
    @RequestMapping(value = "/updateUserInfo.do", method = RequestMethod.POST)
    @ResponseBody
    @AccessPolicy(accessLevel = AccessLevel.PUBLIC,userLevel = UserLevel.REGISTER)
    public RtnData updateUserInfo(UserInfo userInfo, HttpSession session) throws Exception {
        try {
            if (userService.updateTime(userInfo) > 0) {
                return RtnData.ok("保存成功");
            } else {
                return RtnData.fail("保存失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("======编辑感兴趣的行业失败======", e);
            return RtnData.fail("系统繁忙，请稍后再试");
        }
    }

        /**
         * @param userInfo
         * @param session
         * @return
         */
        @RequestMapping(value = "/verification.do", method = RequestMethod.GET)
        @ResponseBody
        public Boolean verification(UserInfo userInfo,HttpSession session) throws Exception {
            Map<String, Object> resultMap = new HashMap<>();
            try {
                /*if ((userInfo.getCode().equalsIgnoreCase(session.getAttribute("code").toString()))) {  //忽略验证码大小写
                    return RtnData.ok(true);
                }*/
                if (userService.verification(userInfo.getUsername()) > 0) {
                    return false;
                }
                if (userService.verification(userInfo.getMobile()) > 0) {
                    return false;
                }
                if (userService.verification(userInfo.getEmail()) > 0) {
                    return false;
                }

            } catch (Exception e) {
                e.printStackTrace();
                logger.error("验证失败");
                return true;
            }
            return true;
        }
    /**
     * @param userInfo
     * @param session
     * @return
     */
    @RequestMapping(value = "/verify.do", method = RequestMethod.GET)
    @ResponseBody
    public Boolean verify(UserInfo userInfo,HttpSession session) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        try {
                /*if ((userInfo.getCode().equalsIgnoreCase(session.getAttribute("code").toString()))) {  //忽略验证码大小写
                    return RtnData.ok(true);
                }*/
            if (userService.verification(userInfo.getUsername()) > 0) {
                return true;
            }
            if (userService.verification(userInfo.getMobile()) > 0) {
                return true;
            }
            if (userService.verification(userInfo.getEmail()) > 0) {
                return true;
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("验证失败");
            return false;
        }
        return false;
    }
    /**
     * 进入登陆页面
     *
     * @return
     */
    @RequestMapping(value = "/login.html")
    public ModelAndView goLogin(HttpServletRequest request,HttpSession session, SessionStatus sessionStatus) {
        session.removeAttribute("userInfo");
        session.removeAttribute("userid");
        sessionStatus.setComplete();
        ModelAndView model = new ModelAndView();
        model.setViewName("user/login");
        String callBack = request.getParameter("callBack");
        if (StringUtil.isNotEmpty(callBack)) {
            model.addObject("callBack",callBack);
        }
        return model;
    }

    @RequestMapping(value = "/goLogin.do", method = RequestMethod.POST)
    @ResponseBody
    public RtnData login(@RequestParam(required = true) String username,
                         @RequestParam(required = true) String password,
                         @RequestParam(required = true) String code, HttpSession session) {
        try {
            if (!code.equalsIgnoreCase(session.getAttribute("code").toString())) {
                return RtnData.fail("验证码错误，请重新输入");
            }
            Map<String, Object> param = new HashMap<>();
            if (StringUtil.isNotEmpty(username)) {
                param.put("username", username);
            }
            if (StringUtil.isNotEmpty(password)) {
                param.put("password", Md5Utils.encodeString(password));
            }
            if(userService.login(param)>0){
                UserInfo userInfo = userService.getUserInfo(param);
                if(userInfo.getState().equals("1")){
                    return RtnData.fail("您的账户被禁用,请联系管理员启用!");
                }
                if (userInfo.getLastLoginTime() == null || "".equals(userInfo.getLastLoginTime())) {
                    userInfo.setLastLoginTime(new Date());
                    userInfo.setFirstLogin(true);
                    userService.updateTime(userInfo);
                }else{
                    userInfo.setFirstLogin(false);
                }
                if(StringUtil.isEmpty(userInfo.getTokenValue())){
                    String tokenValue = SecurityUtil.authentication(param);
                    userInfo.setTokenValue(tokenValue);
                    userInfo.setLastLoginTime(new Date());
                    userService.updateTime(userInfo);
                }
                session.setAttribute("userInfo", userInfo);//用户名
                session.setAttribute("userid", userInfo.getUserid());//用户名
                return RtnData.ok(userInfo);
            }else{
                return RtnData.fail("用户名或密码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("======用户登陆失败======", e);
            return RtnData.fail("系统繁忙，请稍后再试！");
        }
    }
    @RequestMapping(value = "/loginOut.do", method = RequestMethod.GET)
    @ResponseBody
    @AccessPolicy(accessLevel = AccessLevel.PUBLIC,userLevel = UserLevel.REGISTER)
    public RtnData tologout(HttpSession session, SessionStatus sessionStatus) {
        session.removeAttribute("userInfo");
        session.removeAttribute("userid");
        sessionStatus.setComplete();
        return RtnData.ok("退出成功");
    }
    /**
     * 进入个人设置页面
     *
     * @return
     */
    @RequestMapping(value = "/person.html")
    @AccessPolicy(accessLevel = AccessLevel.PUBLIC,userLevel = UserLevel.REGISTER)
    public String person(ModelMap map, HttpServletRequest  request) {
        HttpSession session = request.getSession(false);
        Map intrests = null;
        if(session!=null){
           Integer userid = (Integer) session.getAttribute("userid");
           intrests = userService.getUserIndusty(userid);
        }
        List<Map> intrusty = userService.getIntrustyIn(intrests);
        map.put("choosedIn",intrests);
        map.put("intrustys",intrusty);
        return "user/person";
    }
    @RequestMapping(value = "/getIntrestInduModel.do", method = RequestMethod.GET)
    @ResponseBody
    @AccessPolicy(accessLevel = AccessLevel.PUBLIC,userLevel = UserLevel.REGISTER)
    public RtnData getIntrestInduModel(HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
        Map map = new HashMap();
        map.put("userid",(Integer)session.getAttribute("userid"));
        String intrestIn = userInfo.getIntrestIndus();
        if (intrestIn != null && !intrestIn.equals("")) {
            String[] intrestIns = intrestIn.split(",");
            map.put("industryIds",intrestIns);
        }
        List<Map> list = userService.getIntrestIndustyModel(map);
        return RtnData.ok(list);
    }
    @RequestMapping(value = "/getCommonModel.do", method = RequestMethod.GET)
    @ResponseBody
    @AccessPolicy(accessLevel = AccessLevel.PUBLIC,userLevel = UserLevel.REGISTER)
    public RtnData getCommonModel(HttpSession session) {
        Map map = new HashMap();
        map.put("userid",(Integer)session.getAttribute("userid"));
        List<Map> list = userService.getCommonModel(map);
        return RtnData.ok(list);
    }
    /**
     * 进入第一次选择行业的页面
     * @return
     */
    @RequestMapping(value = "/changePwd.html")
    @AccessPolicy(accessLevel = AccessLevel.PUBLIC,userLevel = UserLevel.REGISTER)
    public String changePwd() {
        return "user/changePwd";
    }
    /**
     * 修改密码
     * @param oldPassword
     * @param newPassword
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/editPwd.json")
    @ResponseBody
    @AccessPolicy(accessLevel = AccessLevel.PUBLIC,userLevel = UserLevel.REGISTER)
    public Object editPwd(
            @RequestParam String oldPassword,
            @RequestParam String newPassword,HttpSession session) throws Exception {
        Map params = new HashMap();
        Integer userid = (Integer) session.getAttribute("userid");
        params.put("oldPassword",Md5Utils.encodeString(oldPassword));
        params.put("newPassword",newPassword);
        params.put("userid",userid);
        if(userService.checkIsTruePwd(params)>0){
            UserInfo userInfo = new UserInfo();
            userInfo.setUserid(userid);
            userInfo.setPassword(Md5Utils.encodeString(newPassword));
            if(userService.updateTime (userInfo)>0){
                return  RtnData.ok("密码修改成功");
            }else{
                return  RtnData.fail("密码修改失败");
            }
        }else{
            return  RtnData.fail("旧密码错误");
        }

    }
    /**
     * 修改头像
     * @param headPhoto
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/editHeadPhoto.json")
    @ResponseBody
    @AccessPolicy(accessLevel = AccessLevel.PUBLIC,userLevel = UserLevel.REGISTER)
    public RtnData editHeadPhoto(
            @RequestParam String headPhoto,HttpSession session) throws Exception {
        Integer userid = (Integer) session.getAttribute("userid");
        UserInfo userInfo = new UserInfo();
        userInfo.setUserid(userid);
        userInfo.setHeadphoto(headPhoto);
        if(userService.updateTime(userInfo)>0){
            return  RtnData.fail("头像修改成功");
        }else{
            return  RtnData.fail("头像修改失败");
        }
    }
    /**
     * 修改头像
     * @param industry
     * @param intrestIndustry
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/doChoose.json")
    @ResponseBody
    @AccessPolicy(accessLevel = AccessLevel.PUBLIC,userLevel = UserLevel.REGISTER)
    public RtnData doChoose(@RequestParam String industry,@RequestParam String intrestIndustry,HttpSession session) throws Exception {
        Integer userid = (Integer) session.getAttribute("userid");
        UserInfo userInfo = new UserInfo();
        userInfo.setUserid(userid);
        userInfo.setIntrestIndus(intrestIndustry);
        userInfo.setIndustryin(industry);
        if(userService.updateTime(userInfo)>0){
            return  RtnData.fail("行业选择成功");
        }else{
            return  RtnData.fail("行业选择失败");
        }
    }
    /**
     * 进入第一次选择行业的页面
     * @return
     */
     @RequestMapping(value = "/init.html")
     @AccessPolicy(accessLevel = AccessLevel.PUBLIC,userLevel = UserLevel.REGISTER)
     public String chooseEnt(ModelMap model) {
         List industrys = userService.getIntrusty();
         model.put("industrys",industrys);
         return "user/init";
     }
}

    /**
     * 进入会员管理页面
     * @return

    @RequestMapping(value = "/getUserList.html")
    public String getUserList() {
        return "user/getList";
    }


    /*
    *
     * 注销登录
     * @param request
     * @return
     * @throws Exception

    @RequestMapping(value="/loginOut.do")
    @ResponseBody
    public RtnData loginOut(HttpServletRequest request) throws Exception{
        HttpSession session = request.getSession(false);
        if (null != session) {
            session.removeAttribute("userInfo");
        }
        return RtnData.ok("注销成功");
    }
    *
     * 查询,列表页面
     *
     * @return

    @RequestMapping(value = "/getlist.do", method = RequestMethod.GET)
    public String getlist(@RequestParam(required = false, defaultValue = "10") long pageSize,
                           @RequestParam(required = false, defaultValue = "1") long page,
                           @RequestParam(required = false) String state,
                           @RequestParam(required = false) String username,
                           @RequestParam(required = false) String startTime,
                           @RequestParam(required = false) String endTime,ModelMap map, HttpServletRequest request) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("state", state);
        params.put("username", username);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        int totalSize = userService.selectCount(params);
        Page pagination = PaginationUtils.getPageParam(totalSize, pageSize, page); //计算出分页查询时需要使用的索引
        params.put("startIndex", pagination.getStartIndex());
        params.put("endIndex", pagination.getEndIndex());
        List users = userService.selectList(params);

        pagination.setUrl(request.getRequestURI());
        map.put("users", users);
        map.put("page", pagination);
        return "user/userTem :: userList";
    }

    *
     * 进入编辑页面
     *
     * @param id
     * @param map
     * @return

    @RequestMapping(value = "/edit.html")
    public String edit(@RequestParam Integer id, ModelMap map) {
        UserInfo userInfo = userService.detail(id);
        map.put("userInfo", userInfo);
        return "user/edit";
    }
    *
     * 进入编辑页面
     *
     * @param userid
     * @param map
     * @return

    @RequestMapping(value = "/getDetails.do")
    public String getDetails(@RequestParam Integer userid, ModelMap map){
        UserInfo userInfo = userService.detail(userid);
        map.put("userInfo", userInfo);
        return "user/detail";
    }

    *
     * 启用用户
     *
     * @param userid
     * @param map
     * @return

    @RequestMapping(value = "/onLine.do", method = RequestMethod.GET)
    @ResponseBody
    public RtnData onLine(Integer userid, ModelMap map) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserid(userid);
        userInfo.setState("0");
        int count = userService.update(userInfo);
        if(count>0){
            return RtnData.ok("启用用户成功");
        }else{
            return RtnData.fail("启用用户失败");
        }

    }
    *
     * 更新用户信息
     *
     * @return

    @RequestMapping(value = "/updateUserInfo.do", method = RequestMethod.POST)
    @ResponseBody
    public RtnData updateUserInfo(UserInfo userInfo) {
        int count = userService.update(userInfo);
        if(count>0){
            return RtnData.ok("修改成功");
        }else{
            return RtnData.fail("修改失败");
        }
    }

    *
     * 禁用用用户
     *
     * @param userid
     * @param map
     * @return

    @RequestMapping(value = "/offLine.do", method = RequestMethod.GET)
    @ResponseBody
    public RtnData offLine(Integer userid, ModelMap map) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserid(userid);
        userInfo.setState("1");
        int count = userService.update(userInfo);
        if(count>0){
            return RtnData.ok("禁用用户成功");
        }else{
            return RtnData.fail("禁用用户失败");
        }

    }

*/
   /*

    *//**
     * 进入新增页面
     *
     * @param map
     * @return
     *//*
    @RequestMapping(value = "/add.html")
    public String add(ModelMap map) {
        List<Category> categorys = userService.findCategorys();
        map.put("categorys", categorys);
        return "book/add";
    }

    *//**
     * 新增
     *
     * @param book
     * @param map
     * @return
     *//*
    @RequestMapping(value = "/addbook.do", method = RequestMethod.POST)
    @ResponseBody
    public RtnData add(Book book, ModelMap map) {
        userService.insertBook(book);
        return RtnData.ok("新增book成功");
    }

    *//**
     * 进入编辑页面
     *
     * @param bookid
     * @param map
     * @return
     *//*
    @RequestMapping(value = "/edit.html")
    public String edit(@RequestParam String bookid, ModelMap map) {
        Long id = Long.parseLong(bookid);
        Book book = userService.selectBookById(id);
        List<Category> categorys = userService.findCategorys();
        map.put("categorys", categorys);
        map.put("book", book);
        return "book/edit";
    }

    *//**
     * 更新
     *
     * @param book
     * @param map
     * @return
     *//*
    @RequestMapping(value = "/updatebook.do", method = RequestMethod.POST)
    @ResponseBody
    public RtnData update(Book book, ModelMap map) {
        userService.updateBook(book);
        return RtnData.ok("修改book成功");
    }

    *//**
     * 删除
     *
     * @param bookid
     * @return
     *//*
    @RequestMapping(value = "/delete.do")
    @ResponseBody
    public RtnData delete(@RequestParam String bookid) {
        Long id = Long.parseLong(bookid);
        userService.deleteBook(id);
        return RtnData.ok("删除book成功");
    }

    @RequestMapping(value = "/listBooks.do")
    @ResponseBody
    public List<Book> listBooks(@RequestParam(required = false, defaultValue = "10") long pageSize,
                                @RequestParam(required = false, defaultValue = "1") long currentPage) {
        Map<String, Object> params = new HashMap<String, Object>();
        int totalSize = userService.findTotalCount(params);
        Page page = PaginationUtils.getPageParam(totalSize, pageSize, currentPage); //计算出分页查询时需要使用的索引
        params.put("startIndex", page.getStartIndex());
        params.put("endIndex", page.getEndIndex());
        List<Book> books = userService.findAll(params);
        return books;
    }*/

